"""
用户控制器模块
处理用户相关的所有HTTP请求
"""
from typing import Optional
from fastapi import APIRouter, Request,Depends, Path, Query, HTTPException, status

from apps.auth.schemas.user_schema import (
    UserCreate, UserUpdate, UserWholeUpdate, UserResponse,
    UserListResponse, SetPasswordRequest
)
from apps.auth.services.user_service import UserService
from pkg.common.utils.response.response import ApiResponse
from pkg.common.constants.response import ResponseCode, ResponseMessage
from pkg.middlewares.auth_middleware import require_superuser, get_current_user
from apps.auth.models.user import User

router = APIRouter(prefix="/users", tags=["用户管理"])


@router.get("", summary="获取用户列表")
async def list_users(
        request: Request,
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        search: Optional[str] = Query(None, description="搜索关键词"),
        status: Optional[int] = Query(None, description="用户状态过滤"),
        role: Optional[str] = Query(None, description="用户角色过滤")
):
    """
    获取用户列表
    可以提供分页、搜索和过滤参数
    """
    # 获取当前登入用户
    # user = request.state.user

    users, total = await UserService.list_users(
        page=page,
        page_size=page_size,
        search=search,
        status=status,
        role=role
    )

    # 使用统一响应格式
    return ApiResponse.paginate(
        items=[UserResponse.model_validate(user) for user in users],
        total=total,
        page=page,
        page_size=page_size
    )


@router.get("/{user_id}", summary="获取用户详情")
async def get_user(
        user_id: int = Path(..., gt=0, description="用户ID")
):
    """
    通过ID获取用户详情
    """
    user = await UserService.get_user_by_id(user_id)

    # 使用统一响应格式
    return ApiResponse.success(
        data=UserResponse.model_validate(user),
        msg=f"成功获取用户ID {user_id} 的信息"
    )


@router.post("", status_code=status.HTTP_201_CREATED, summary="创建用户")
async def create_user(
        user_data: UserCreate
):
    """
    创建新用户
    """
    user = await UserService.create_user(user_data.model_dump())

    # 使用统一响应格式
    return ApiResponse.success(
        data=UserResponse.model_validate(user),
        msg="用户创建成功",
        code=ResponseCode.SUCCESS
    )


@router.put("/{user_id}", summary="更新用户信息")
async def update_user(
        user_data: UserUpdate,
        user_id: int = Path(..., gt=0, description="用户ID")
):
    """
    部分更新用户信息
    只更新提供的字段
    """
    user = await UserService.update_user(user_id, user_data.model_dump(exclude_unset=True))

    # 使用统一响应格式
    return ApiResponse.success(
        data=UserResponse.model_validate(user),
        msg="用户更新成功"
    )


@router.put("/{user_id}/whole", summary="更新用户信息")
async def update_user_whole(
        user_data: UserWholeUpdate,
        user_id: int = Path(..., gt=0, description="用户ID")
):
    """
    全量更新用户信息
    更新所有字段
    """
    user = await UserService.update_user_whole(user_id, user_data.model_dump())

    # 使用统一响应格式
    return ApiResponse.success(
        data=UserResponse.model_validate(user),
        msg="用户全量更新成功"
    )


@router.delete("/{user_id}", summary="删除用户")
async def delete_user(
        user_id: int = Path(..., gt=0, description="用户ID")
):
    """
    软删除用户(逻辑删除)
    """
    await UserService.delete_user(user_id)

    # 使用统一响应格式
    return ApiResponse.success(
        data=None,
        msg=f"用户ID {user_id} 已成功删除"
    )


@router.delete("/{user_id}/true", summary="硬删除用户")
async def hard_delete_user(
        user_id: int = Path(..., gt=0, description="用户ID"),
        current_user: User = Depends(require_superuser)
):
    """
    硬删除用户(物理删除)
    """
    await UserService.hard_delete_user(user_id)

    # 使用统一响应格式
    return ApiResponse.success(
        data=None,
        msg=f"用户ID {user_id} 已永久删除"
    )


@router.put("/{user_id}/password", summary="设置用户密码")
async def set_user_password(
        password_data: SetPasswordRequest,
        user_id: int = Path(..., gt=0, description="用户ID")
):
    """
    设置用户密码
    """
    await UserService.set_user_password(user_id, password_data.password)

    # 使用统一响应格式
    return ApiResponse.success(
        data=None,
        msg="密码更新成功"
    )
